#!/usr/bin/python

###############################################################
## Name       : svn_back
## Author     : xiaotu
## Time       : 2022-07-23 11:48:35
## Description:
## 
## 
###############################################################

import sys
import os
import re
import argparse
import math

def main():
    print("%s is working" % __file__)
    file_name = sys.argv[1]
    file_name = re.sub(r"/$", "", file_name)
    
    #step1, mv sel_file
    if os.path.exists(r"{0}_loc".format(file_name)):
        print(r"exists {0}_loc, please check".format(file_name))
        sys.exit()
    os.system(r"mv -f {0} {0}_loc".format(file_name))

    #step2, svn up sel_file
    os.system(r"svn up {0}".format(file_name))
    svn_log_list = os.popen("svn log -l2 {0}".format(file_name)).readlines()

    #step3, get now svn and latest svn
    latest = 0
    now_svn = "r0"
    latest_svn = "r0"
    for log in svn_log_list:
        log = log.strip()
        res = re.match(r"(r\d+)\s+", log)
        if res:
            if latest == 0:
                now_svn = res.group(1)
                latest = 1
            else:
                latest_svn = res.group(1)
                latest = 0
                break
    
    if latest == 1: #only 1 version
        print("only single version, cannot back")
        sys.exit()

    #step4, get back svn
    if len(sys.argv) > 2:
        back_svn = sys.argv[2]
    else:
        back_svn = latest_svn
    
    #step5, svn up back_svn
    os.system(r"svn up -{0} {1}".format(back_svn, file_name))
    os.system(r"mv -f {0} {0}_bak".format(file_name))
    os.system(r"svn up {0}".format(file_name))
    
    #step6, replace back_svn
    if os.path.isfile(file_name):
        os.system(r"mv -f {0}_bak {0}".format(file_name))
    else:
        os.system(r"mv -f {0}_bak/* {0}/*".format(file_name))
        os.system(r"rm -rf {0}_bak".format(file_name))
    
    #step7, svn ci
    os.system(r"svn ci -m 'svn back from {0} to {1}' {2}".format(now_svn, back_svn, file_name))
    os.system(r"svn up {0}".format(file_name))
    os.system(r"svn log -l1 {0}".format(file_name))

if __name__ == "__main__":
    main()
